package Tree;

import java.util.ArrayList;

/**
 * @Classname JZ54二叉搜索树的第k大节点
 * @Description TODO
 * @Date 2023/2/23 8:58
 * @Created by xjl
 */
public class JZ54二叉搜索树的第k大节点 {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    /**
     * @description 使用中序遍历来实现
     * @param: root
     * @param: k
     * @date: 2023/2/23 9:00
     * @return: int
     * @author: xjl
     */
    public int kthLargest(TreeNode root, int k) {
        if (root == null) {
            return 0;
        }
        ArrayList<Integer> list = new ArrayList<>();
        dfs(root, list);
        if (k > list.size()) {
            return 0;
        }
        return list.get(list.size() - k);
    }

    /**
     * @description 二叉树的中序遍历
     * @param: root
     * @param: list
     * @date: 2023/2/23 9:04
     * @return: void
     * @author: xjl
     */
    private void dfs(TreeNode root, ArrayList<Integer> list) {
        if (root == null) {
            return;
        }
        if (root.left != null) {
            dfs(root.left, list);
        }
        list.add(root.val);
        if (root.right != null) {
            dfs(root.right, list);
        }
    }

    int res, k;

    public int kthLargest2(TreeNode root, int k) {
        this.k = k;
        dfs2(root);
        return res;
    }

    void dfs2(TreeNode root) {
        if (root == null) {
            return;
        }
        dfs2(root.right);
        //如果k==0 就表示提前终止
        if (k == 0) {
            return;
        }
        // 如果不等于0的话那就是更新res的值
        if (--k == 0) {
            res = root.val;
        }
        dfs2(root.left);
    }
}
